package com.psjj.privilege.web.filter;

import com.psjj.privilege.po.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获得session中的用户信息
        User user = (User)req.getSession().getAttribute("user");
        //访问登录方法不用判断直接放行
        String method = req.getParameter("method");
        //登录成功
        if("login".equals(method)){
            filterChain.doFilter(req,resp);
        } else if (user!=null ){
            //获得当前访问路径
            String uri = req.getRequestURI();
            //获得权限控制的访问路径格式
            String filterUrl = uri.replace(req.getContextPath(),"")+"?method="+method;
            //判断当前用户是否拥有此权限 拥有方法 不拥有拦截到权限不足页面
            if(user.hasPrivilegeByUrl(filterUrl)){
                filterChain.doFilter(req,resp);
            }else {
                resp.sendRedirect(req.getContextPath()+"/noprivilege.jsp");
            }
        }else {
            //登录失败，重定向到登录页面
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }


    }

    @Override
    public void destroy() {

    }
}
